<template>
  <div style="margin-bottom: 20px;height: auto;margin-left: 20px;margin-top: -70px;width: 800px;float: left;">
    <el-row style="width: 330px;margin-left: 820px;margin-bottom: -50px;margin-top: 60px">
      <el-button type="success" style="width: 330px;" @click="dialogFormVisible = true">我要发贴</el-button>
    </el-row>
    <el-col v-for="(item, index) in displayedData" :key="index" :span="16" :offset="index > 0 ? 0 : 0">
      <el-card :body-style="{ padding: '5px' }" style="width: 800px;margin-top: 20px;">
        <div style="padding: 14px">
          <span>{{ item.postDesc }}</span> <!-- 假设每个对象有一个title属性 -->
        </div>
        <img v-for="(image, index) in item.postImgs" :key="index" :src="image"
          style="margin-left: 20px;margin-bottom: 10px;width: 100px;height: 100px;" />
        <!-- 假设每个对象有一个imageUrl属性 -->
        <div style="margin-left: 10px;">
          <el-button :type="item.buttonType" plain style="width: 100px;" @click="golike(item.postId)">
            <Pointer style="width: 1em; height: 1em; margin-right: 8px" />点赞&nbsp;<span>{{
              item.likeNum
            }}</span>
          </el-button>
          <el-button type="info" plain style="width: 100px;" @click="gocomment(item.postId)">
            <Comment style="width: 1em; height: 1em; margin-right: 8px" />评论&nbsp;<span>{{
              item.commentNum }}</span>
          </el-button>
          <span style="margin-left: 20px;">作者：{{ item.author }}</span>

        </div>
      </el-card>

    </el-col>
    <!-- 分页 -->
    <div class="paging" style="margin-top: 20px;">
      <el-pagination background layout="prev, pager, next" :total="total" v-model:current-page="currentPage"
        v-model:page-size="pageSize" @current-change="handleCurrentChange" />
    </div>
  </div>
  <el-dialog v-model="dialogFormVisible" title="我要发贴">



    <template #footer>
      <div>
        <el-input v-model="textarea" :rows="2" type="textarea" placeholder="输入文字..." style="margin-top: -30px;" />
      </div>
      <!-- <div style="margin-top: 20px;">

    <div class="feedback_wrapper" style="margin-left: 120px;">
      <el-upload :class="'upload_wrapper' + (hideUpload ? 'hide' : '')" list-type="picture-card" :limit="9"
        :file-list="fileList" :show-file-list="true" :on-change="fileChange" :auto-upload="false" accept="image/*">
        <el-icon>
          <Plus />
        </el-icon>
        <template #file="{ file }">
          <div style="width: 200px; height: 200px;">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt style="width: 200px; height: 150px;" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <el-icon>
                  <zoom-in />
                </el-icon>
              </span>
             
            </span>
          </div>
        </template>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full class="full_img" :src="dialogImageUrl" alt="Preview Image" style="width: 800px; height: 300px;" />
      </el-dialog>
    </div>



  </div> -->

      <div style="margin-top: 20px;">
        <el-button @click="nook">取消</el-button>
        <el-button type="primary" @click="submit()">
          确认发贴
        </el-button>
      </div>

    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import { ref, reactive, computed } from 'vue'
import axios from '../../api/index';
import { da, el } from 'element-plus/es/locale';
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';
const router = useRouter();
const dialogFormVisible = ref(false)

const carouselData = ref([] as any[]);


// 从localStorage中获取存储的JSON字符串  
const userInfoJsonString = localStorage.getItem('userInfo')!;

// 解析JSON字符串为JavaScript对象  
const userInfo = JSON.parse(userInfoJsonString);
// import axios from 'axios' // 引入axios库进行HTTP请求  



const data = reactive([] as any[]) // 用于存储后端传回的数据  


findPosts();

function findPosts() {

  data.splice(0);

  if (userInfo.id != null || userInfo.id != '') {


    axios.get('/post/postList')
      .then((resp) => {
        if (resp.code = 200) {

          total.value = resp.data.length
          for (let index = 0; index < resp.data.length; index++) {

            const buttonType = ref('')

            //根据resp.data[index].userId查询发帖人信息
            axios.get('/user/' + resp.data[index].userId)
              .then((resp1) => {
                if (resp1.code == 2001) {

                  //查询用户是否点赞
                  axios.get('/postlike/findPostLike?postId=' + resp.data[index].postId + '&userId=' + userInfo.id)
                    .then((resp2) => {
                      if (resp2.code == 200) {
                        buttonType.value = 'success'
                      } else {
                        buttonType.value = 'info'
                      }
                      data.push({
                        postId: resp.data[index].postId,
                        postImgs: resp.data[index].postImgs,
                        postDesc: resp.data[index].postContent,
                        likeNum: resp.data[index].likeNum,
                        commentNum: resp.data[index].commentNum,
                        author: resp1.data.nickname,
                        postLikes: resp.data[index].postLikes,
                        comments: resp.data[index].comments,
                        buttonType: buttonType.value
                      })
                    })


                }

              })



          }

        }
      })


  }
}




//跳转到贴子的评论区
function gocomment(postId: any) {
  router.push('/comment/' + postId)
}




//点赞
function golike(postId: any) {

  //先查询该用户是否点赞了该贴子
  axios.get('/postlike/findPostLike?postId=' + postId + '&userId=' + userInfo.id)
    .then((resp) => {
      // code：200 该用户已经点赞了该贴子
      if (resp.code == 200) {

        //所以点击点赞按钮时，会删除这条点赞
        axios.delete('/postlike/delPostLike?postLikeId=' + resp.data.postLikeId)
          .then((resp1) => {
            if (resp1.code == 200) {
              //删除成功！
              //重新调用findPosts方法

              findPosts();
            } else {
              //删除失败
              ElMessage.error('取消点赞失败！')
            }
          })
      } else {
        //用呼没有点赞该贴子
        //所以点击时，会添加点赞
        axios({
          method: 'POST',
          url: '/postlike/savePostLike',
          data: JSON.stringify({
            postId: postId,
            userId: userInfo.id
          }),
          headers: {
            'Content-Type': 'application/json'
          }
        }).then((resp2) => {
          if (resp2.code == 200) {

            //点赞成功！

            //重调findPosts方法
            findPosts();
          } else {
            ElMessage.error('点赞失败了！')
          }
        })

      }
    })
}






//删除贴子
// function delPost(postId: any) {
//     axios.put('/post/deletePost?postId=' + postId)
//         .then((resp) => {
//             if (resp.code == 200) {
//                 dialogFormVisible.value = false
//                 ElMessage.success(resp.msg);
//                 findPosts();

//             } else {
//                 dialogFormVisible.value = false
//                 ElMessage.error(resp.msg);
//             }
//         })
// }



// 在组件创建时发起HTTP请求获取数据
// function async created() {
//   try {
//     const response = await axios.get('/api/data') // 替换为你的后端API地址
//     data.value = response.data // 将获取到的数据赋值给data变量
//   } catch (error) {
//     console.error(error)
//   }
// }

function nook() {
  dialogFormVisible.value = false;
  textarea.value = '';
  fileList.value.splice(0)
}

const textarea = ref('')




//========图片上传





const fileList = ref([]); // 图片列表
const dialogImageUrl = ref(""); // 预览图url
const dialogVisible = ref(false); // 预览弹窗
const hideUpload = ref(false); // 是否隐藏上传按钮
var formData = new FormData(); //文件上传
// 更新上传加号按钮显示状态
function updateUploadShown() {
  if (fileList.value.length == 9) {
    hideUpload.value = true;
  } else {
    hideUpload.value = false;
  }
}
// 文件改变
function fileChange(file: any, resfileList: any) {
  fileList.value = resfileList;
  formData.append("file", file.raw)
  updateUploadShown();
}

// 移除图片
const handleRemove = (file: any) => {
  // const list = fileList.value;
  // for (const i in list) {
  //   if (list[i].uid === file.uid) {
  //     list.splice(i, 1);
  //   }
  // }
  // fileList.value = list;


  // console.log(formData);
  updateUploadShown();
};

// 预览图片
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};







function submit() {


  if (textarea.value == '') {
    ElMessage.error('输入不能为空！')
  } else {
    if (textarea.value.length > 2000) {
      ElMessage.error('最多输入2000字！')
    } else {
      axios({
        method: 'POST',
        url: '/post/savePost',
        data: JSON.stringify({
          userId: userInfo.id,
          postContent: textarea.value
        }),
        headers: {
          'Content-Type': 'application/json'
        }
      }).then((resp) => {
        if (resp.code == 200) {

          ElMessage.success("发布成功！")
          nook();

          location.reload();

        } else {
          ElMessage.error('发布失败！')
        }
      })

      // axios.post('/post/savePostAndImgs', post)
      //   .then((resp) => {
      //     if (resp.code == 200) {

      //       ElMessage.success('发布成功！')
      //       formData.delete("file")
      //       formData.delete("userId")
      //       formData.delete("postContent")
      //       nook();
      //       getcarouseData();
      //     } else {
      //       ElMessage.error("发布失败！")
      //     }
      //   })

    }
  }

}



//分页组件======================

//分页实现
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 监听currentPage和tableData变化，计算显示的数据
const displayedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return data.slice(start, end);
});

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}



//=========================



</script>